package org.budo.elasticsearch.jdbc.driver.statement;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.budo.elasticsearch.jdbc.driver.BudoElasticsearchJdbcConnection;
import org.budo.elasticsearch.jdbc.driver.BudoElasticsearchJdbcPreparedStatement;
import org.budo.jdbc.driver.resultset.impl.ObjectArrayResultSet;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.common.collect.ImmutableOpenMap;

import com.carrotsearch.hppc.ObjectLookupContainer;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectObjectCursor;

/**
 * @author li
 */
public class SHOW_TABLES extends AbstractElasticsearchStatement {
    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException {
        BudoElasticsearchJdbcConnection connection = (BudoElasticsearchJdbcConnection) preparedStatement.getConnection();
        TransportClient transportClient = connection.getTransportClient();

        String index = connection.getCatalog();

        ImmutableOpenMap<String, ImmutableOpenMap<String, MappingMetaData>> mappings = transportClient.admin() //
                .indices() //
                .prepareGetMappings(index) //
                .get() //
                .getMappings();

        List<String> types = new ArrayList<String>();
        for (ObjectObjectCursor<String, ImmutableOpenMap<String, MappingMetaData>> cursor : mappings) {
            ObjectLookupContainer<String> keys = cursor.value.keys();
            for (ObjectCursor<String> objectCursor : keys) {
                types.add(objectCursor.value);
            }
        }

        String[] valueArray = types.toArray(new String[types.size()]);
        ObjectArrayResultSet resultSet = new ObjectArrayResultSet(new String[] { "Tables_in_" + index },valueArray);

        ((BudoElasticsearchJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }
}
